from spargameproject.spargame.game.engine.game_engine import PlayHandler
from spargameproject.spargame.game.playhandlers.spar_play_handlers import getSparDeck

class DealHandler(PlayHandler):
  def getType(self):
    return 'deal'

  def handlePlay(self, play, game_engine):
    print 'Just handled a play of type: ' + self.getType()
    game = play.game
    active_players = game.getActiveGamePlayers()
    message = 'Dealt cards for %s players' % len(active_players)
    play.setMetadata('message', message)
    old_session = game.getMetadata('session')
    session = old_session + 1
    play.setMetadata('session', session)
    cards_needed = len(active_players) * 5
    game.setMetadata('session', session)
    deck = game.getMetadata('game_deck')

    if len(deck) < cards_needed:
      deck = getSparDeck()
    for game_player in active_players:
      current_hand = deck[:5]
      deck = deck[5:]
      game_player.setMetadata('current_cards_left', current_hand)
      game_player.setMetadata('win_stack', [])
      game_player.setMetadata('dry_win_stack', [])
      game_player.setMetadata('cards_left', current_hand)
      game_player.setMetadata('lost', False)
      game_player.setMetadata('dry_card_indeces', [])
      game.setMetadata('lost_players', [])
      hand = game_player.getMetadata('hand') or {session: current_hand}
      hand[session] = current_hand
      game_player.setMetadata('hand', hand)
      if not game_player.getMetadata('is_bot'):
        game_player.setMetadata('ready', False)
    game.setMetadata('game_deck', deck)
    game.setMetadata('players_played', set())
    game.setMetadata('card_to_beat', '')
    game.setMetadata('lead_player', play.player.id)
    game.setMetadata('in_progress', True)
    game.setMetadata('ready', False)
    response = {'message': message}
    return [], response
